﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ROrganizer.Client;
using ROrganizer.Client.Files;
using ROrganizer.UI.Controllers;
using ROrganizer.UI.Forms.Core;

namespace ROrganizer.UI.Forms
{
    internal partial class ProgressForm : Form
    {
        private readonly ProgressFormController controller;

        public ProgressForm(CopyTask[] tasks)
        {
            this.controller = new ProgressFormController(tasks, exceptioner: this.ProcessException);
            this.InitializeComponent();

            this.controller.Changed += this.OnChanged;
        }

        public ProgressForm(RemoveTask[] tasks)
        {
            this.controller = new ProgressFormController(tasks, exceptioner: this.ProcessException);
            this.InitializeComponent();

            this.controller.Changed += this.OnChanged;
        }

        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);
            this.RefreshActions();
            this.controller.Start();
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            e.Cancel = this.controller.IsWorking && !this.controller.IsCompleted;
            base.OnClosing(e);
        }

        private void OnChanged(object sender, EventArgs e)
        {
            if (this.SynchronizeInvocation(this.OnChanged, sender, e))
            {
                this.lblAction.Text = this.controller.Action;
                this.lblTarget.Text = this.controller.Item;
                this.pbMain.Value = Math.Min(this.controller.Progress, this.pbMain.Maximum);
                this.RefreshActions();

                if (this.controller.IsCompleted)
                    this.Close();
            }
        }

        private void OnCancel(object sender, EventArgs e)
        {
            this.controller.Cancel();
            this.RefreshActions();
        }

        private void RefreshActions()
        {
            this.btnCancel.Enabled = this.controller.CanCancel();
        }
    }
}
